import adminApi from '@/services/adminApi';
import type { ProFormInstance } from '@ant-design/pro-components';
import {
  DrawerForm,
  ProForm,
  ProFormGroup,
  ProFormRadio,
  ProFormText,
} from '@ant-design/pro-components';
import { message, Tree } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
export type UpdateRoleProps = {
  onCancel: (flag?: boolean) => void;
  onSubmit: (values: any) => Promise<void>;
  showUpdateRole: number;
  values: any;
};
const UpdateRole: React.FC<UpdateRoleProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [treeData, setTreeData] = useState<any>([]);
  const getTreeData = async () => {
    const res = await adminApi.cwSys.AdminapiCwSysRolenode({ mod_id: 1 });
    setTreeData(res.data);
  };
  useEffect(() => {
    getTreeData();
  }, []);
  useEffect(() => {
    if (props.showUpdateRole == 2) {
      console.log('fdsafsa', props.values);
      const v: any = {};
      v.name = props?.values?.name;
      v.state = props?.values?.state;
      v.desc = props?.values?.desc;
      v.id = props?.values?.id;
      formRef.current?.setFieldsValue(v);
      console.log(props?.values?.menu_ids?.split(','));
      setCheckedKeys([
        props?.values?.checkedKeysValue?.split(',').map(Number),
        props?.values?.halfCheckedKeys?.split(',').map(Number),
        [
          ...props?.values?.checkedKeysValue?.split(',').map(Number),
          ...props?.values?.halfCheckedKeys?.split(',').map(Number),
        ],
      ]);
    }
  }, [props]);
  const onCheck: any = (checkedKeysValue: React.Key[], info: any) => {
    console.log('onCheck', checkedKeysValue, info);
    setCheckedKeys([
      checkedKeysValue,
      info.halfCheckedKeys,
      [...checkedKeysValue, ...info.halfCheckedKeys],
    ]);
  };
  // const onSelect = (selectedKeysValue: React.Key[], info: any) => {
  //   console.log('onSelect', info);
  //   // setCheckedKeys([...selectedKeysValue, ...info.halfCheckedKeys]);
  // };

  return (
    <DrawerForm<{
      name: string;
      company: string;
    }>
      title={props?.showUpdateRole == 1 ? '新建角色' : '编辑角色'}
      formRef={formRef}
      visible={props.showUpdateRole !== 0}
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
        maskClosable: true,
        onClose: () => {
          setCheckedKeys([]);
          props?.onCancel();
        },
      }}
      onFinish={async (values: any) => {
        if (checkedKeys.length > 0) {
          values.menu_ids = checkedKeys[2];
          values.checkedKeysValue = checkedKeys[0];
          values.halfCheckedKeys = checkedKeys[1];
        } else {
          message.error('请选择权限节点');
          return true;
        }
        if (props.showUpdateRole == 2) {
          values.id = props.values.id;
        }
        // console.log(values);
        props?.onSubmit(values);
        // 不返回不会关闭弹框
        return true;
      }}
    >
      <ProForm.Group>
        <ProFormText
          name="name"
          width="md"
          label="角色名称"
          tooltip="最长为 24 位"
          placeholder="请输入名称"
          rules={[{ required: true }]}
        />
        <ProFormRadio.Group
          name="state"
          label="状态"
          radioType="button"
          initialValue={true}
          options={[
            {
              label: '启用',
              value: true,
            },
            {
              label: '禁用',
              value: false,
            },
          ]}
          rules={[{ required: true }]}
        />
      </ProForm.Group>
      <ProFormText name="desc" label="备注" placeholder="请输入备注" />
      <ProFormGroup label="权限节点" titleStyle={{ marginBottom: 0 }} tooltip="必选">
        <Tree
          checkable
          // onExpand={onExpand}
          // expandedKeys={expandedKeys}
          // autoExpandParent={autoExpandParent}
          defaultCheckedKeys={
            props.showUpdateRole == 2 ? props?.values?.checkedKeysValue?.split(',').map(Number) : []
          }
          onCheck={onCheck}
          // onSelect={onSelect}
          treeData={treeData}
          showLine={{ showLeafIcon: false }}
          fieldNames={{ title: 'name', key: 'id' }}
          defaultExpandAll={true}
        />
      </ProFormGroup>
    </DrawerForm>
  );
};
export default UpdateRole;
